package com.villaday.idf.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.adapter.MessageList2Adapter;
import com.villaday.idf.adapter.MessageListAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.DownloadDialog;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.NewVersionDialog;
import com.villaday.idf.custom.DividerItemDecoration.RVItemDecoration;
import com.villaday.idf.model.LoginEntity;
import com.villaday.idf.model.MemberMessagEntity;
import com.villaday.idf.model.UpgradeEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

public class MessageListType0Activity extends BaseActivity implements OkHttpUtil.OnDataListener, AbsRecyclerViewAdapter.OnItemClickListener, OnAdapterCallbackListener, View.OnClickListener, OkHttpUtil.OnProgressListener {

    @BindView(R.id.toolbar_text)
    Toolbar toolbarText;
    @BindView(R.id.rv)
    RecyclerView rv;
    private Gson gson = new GsonBuilder().create();
    private int messageType;
    private MessageListAdapter messageList0Adapter;
    private LoadingDialog loadingDialog;
    private MessageList2Adapter messageList2Adapter;
    private MemberMessagEntity memberMessagEntity;

    private boolean isNeedLoad = false;

    private boolean isForce = false;//是否强制升级
    private String versionName;
    private String newAppLink;
    private DownloadDialog downloadDialog;
    private String filePath;
    private Handler handler = new Handler();

    @Override
    protected int getViewResId() {
        return R.layout.activity_message_list_type0;
    }

    @Override
    protected void init() {
        messageType = getIntent().getIntExtra("messageType", 0);
        ToolBarUtil.initToolBar(toolbarText, "消息中心", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                onBackPressed();
            }
        });

        if (messageType == 2) {
            rv.setLayoutManager(new LinearLayoutManager(this));
            messageList2Adapter = new MessageList2Adapter(this, this, this);
            rv.setAdapter(messageList2Adapter);
            rv.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(this, 7), getResources().getColor(R.color.colorBg), PhoneUtil.dp2px(this, 8)));

            messageList2Adapter.setOnItemClickListener(this);
            messageList2Adapter.setEmptyView(R.layout.empty_tips);
            messageList2Adapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");
        } else {
            rv.setLayoutManager(new LinearLayoutManager(this));
            messageList0Adapter = new MessageListAdapter(this, this, this);
            rv.setAdapter(messageList0Adapter);
            rv.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(this, 7), getResources().getColor(R.color.colorBg), PhoneUtil.dp2px(this, 8)));

            messageList0Adapter.setOnItemClickListener(this);
            messageList0Adapter.setEmptyView(R.layout.empty_tips);
            messageList0Adapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");


        }
    }

    @Override
    protected void loadData() {
        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getFragmentManager(), "loading");
        OkHttpUtil.getJSON(this, String.format(Constant.URL.member_messag, messageType), this);
    }

    @Override
    public void onResponse(String url, String json) {
        dismissLoading();
        if (!TextUtils.isEmpty(json)) {
            if (String.format(Constant.URL.member_messag, messageType).equals(url)) {
                LogeUtil.e("member_messag", json);
                memberMessagEntity = gson.fromJson(json, MemberMessagEntity.class);
                if (messageType == 2) {
                    messageList2Adapter.setData(memberMessagEntity.getBody().getList());
                } else {
                    messageList0Adapter.setData(memberMessagEntity.getBody().getList());
                }
            } else if (Constant.URL.upgrade.equals(url)) {
                dismissLoading();
                LogeUtil.e("upgrade", json);
                final UpgradeEntity upgradeEntity = gson.fromJson(json, UpgradeEntity.class);
                if ("200".equals(upgradeEntity.getCode())) {
                    if (!upgradeEntity.getBody().isUpgradeable()) {
                        ToastUtil.initToast(this, "已是最新版本");

                    }
                    isForce = false;
                    versionName = upgradeEntity.getBody().getBundleVersion();
                    String charStr = versionName.charAt(0) + "";
                    String ver = versionName;
                    if ("V".equals(charStr) || "v".equals(charStr)) {
                        ver = versionName.substring(1, versionName.length());
                    }
                    if ("V".equals(charStr)) {
                        isForce = true;
                    }
                    int isNeedUpdate = PhoneUtil.isNeedUpdate(PhoneUtil.getAppVersion(this), ver);
                    switch (isNeedUpdate) {
                        case 2://需要强制更新
                            isForce = true;
                        case 1://需要更新

                            String newContent = upgradeEntity.getBody().getMessage() + "</br>(建议在wifi下更新)";
                            NewVersionDialog newDialog = NewVersionDialog.newInstance(ver,
                                    newContent.replace("</br>", "\n"), isForce == true ? "force" : "取消", "更新");
                            newDialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                                @Override
                                public void onItemClick(View v) {
                                    downLoadApp(upgradeEntity.getBody().getBundleVersion(), upgradeEntity.getBody().getUrl());
                                }
                            });
                            newDialog.show(getFragmentManager());
                            break;
                        default: {
                            ToastUtil.initToast(this, "已是最新版本");
                        }
                        break;
                    }
                }
            }

        }
    }

    @Override
    public void onFailure(String url, String error) {

    }

    private void downLoadApp(String versionName, String url) {
        downloadDialog = DownloadDialog.newInstance(PhoneUtil.getAppName(this) + versionName, isForce);
        downloadDialog.show(getFragmentManager(), "download");
        filePath = Environment.getExternalStorageDirectory() + "/Download/" + PhoneUtil.getAppName(this) +
                "_" + versionName + ".apk";
        Log.e("loge", "Download: " + filePath);
        OkHttpUtil.fileDownload(url, filePath, this, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {//下载完成
                TextView btnInstall = downloadDialog.getBtnInstall();
                btnInstall.setSelected(true);
                btnInstall.setText("安装");
                btnInstall.setClickable(true);
                btnInstall.setOnClickListener(MessageListType0Activity.this);
                jumpInstall();
            }

            @Override
            public void onFailure(String url, String error) {
            }
        });
    }

    /**
     * 跳转到安装页面
     */
    private void jumpInstall() {
        File apkFile = new File(filePath);
        if (apkFile.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");

            } else {

                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);//给目标应用一个临时的授权
                Uri uriForFile = FileProvider.getUriForFile(this, PhoneUtil.getAppProcessName(this) + ".FileProvider", apkFile);
                intent.setDataAndType(uriForFile, "application/vnd.android.package-archive");

            }
            startActivity(intent);
            android.os.Process.killProcess(android.os.Process.myPid());


        }
    }

    @Override
    public void onItemClick(View v, int position) {
        if (memberMessagEntity != null && memberMessagEntity.getBody() != null && memberMessagEntity.getBody().getList().size() != 0) {
            //列表取消红点
            if (memberMessagEntity.getBody().getList().get(position).getReadState() == 0) {
                isNeedLoad = true;
                memberMessagEntity.getBody().getList().get(position).setReadState(1);
                if (messageType == 2) {
                    messageList2Adapter.notifyDataSetChanged();
                } else {
                    messageList0Adapter.notifyDataSetChanged();
                }

                OkHttpUtil.getJSON(this, String.format(Constant.URL.member_message_read, memberMessagEntity.getBody().getList().get(position).getId()), this);
            }
            // "type": integer, 0无跳转，1跳转APP页面，2链接跳转内嵌webView,3 版本更新
            if (memberMessagEntity.getBody().getList().get(position).getExtras().getType() == 1) {
                //跳转APP页面
                /*
                *   "idfAppPage": string, 定义的页面路径,
                    "params": {
                     id: "xxxxxx", app页面对应的参数，后期根据需要补充
                               },
                * */

                if ("page/home".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/home";  首页

                    Intent intent = getIntent();
                    intent.putExtra("type", "page/home");
                    setResult(RESULT_OK, intent);
                    finish();

                } else if ("page/home/material".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/home/material";  首页-动态(material)
                    Intent intent = getIntent();
                    intent.putExtra("type", "page/home/material");
                    setResult(RESULT_OK, intent);
                    finish();
                } else if ("page/home/presell".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/home/presell";  首页-特卖(presell)
                    Intent intent = getIntent();
                    intent.putExtra("type", "page/home/presell");
                    setResult(RESULT_OK, intent);
                    finish();
                } else if ("page/home/topic".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/home/topic";  首页-发现(topic)
                    Intent intent = getIntent();
                    intent.putExtra("type", "page/home/topic");
                    setResult(RESULT_OK, intent);
                    finish();
                } else if ("page/village".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/village";  目的地列表页
                    Intent intent = getIntent();
                    intent.putExtra("type", "page/village");
                    setResult(RESULT_OK, intent);
                    finish();

                } else if ("page/village/detail".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/village/detail";  目的地详情页
                    Intent intent = new Intent(MessageListType0Activity.this, BourbonListActivity.class);

                    intent.putExtra("villageId", memberMessagEntity.getBody().getList().get(position).getExtras().getParams().getId());
                    intent.putExtra("city", "");
                    intent.putExtra("area", "");
                    startActivity(intent);
                } else if ("page/search".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/search";  房源搜索索引页

                    Intent intent = new Intent(this, SearchBournActivity.class);
                    intent.putExtra("cityId", memberMessagEntity.getBody().getList().get(position).getExtras().getParams().getId());
                    startActivity(intent);
                } else if ("page/search/result".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/search/result";  房源搜索结果页
                    Intent intent = new Intent(this, BourbonListActivity.class);
                    intent.putExtra("villageId", memberMessagEntity.getBody().getList().get(position).getExtras().getParams().getId());
                    intent.putExtra("city", "");
                    intent.putExtra("area", "");
                    startActivity(intent);
                } else if ("page/house/detail".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/house/detail";  房源详情页
                    //普通房源
                    Intent intent = new Intent(this, HouseDetailsActivityFor3.class);
                    intent.putExtra("houseId", memberMessagEntity.getBody().getList().get(position).getExtras().getParams().getId());
                    intent.putExtra("persellId", "");
//                    intent.putExtra("type", data.get(position).getType());
                    startActivity(intent);

                } else if ("page/presell/detail".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/presell/detail";  房源详情页
                    //特卖房源
                    Intent intent = new Intent(this, HouseDetailsActivityFor3.class);
                    intent.putExtra("houseId", memberMessagEntity.getBody().getList().get(position).getExtras().getParams().getId());
                    intent.putExtra("persellId", memberMessagEntity.getBody().getList().get(position).getExtras().getParams().getId());
                    intent.putExtra("presellProduct", true);
//                    intent.putExtra("type", data.get(position).getType());
                    startActivity(intent);

                } else if ("page/vip".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/vip";  VIP
                    Intent intent = getIntent();
                    intent.putExtra("type", "page/vip");
                    setResult(RESULT_OK, intent);
                    finish();
                } else if ("page/vip/share".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/vip/share";  vip邀请好友分享页
                    startActivity(new Intent(this, InviteFriendActivity.class));

                } else if ("page/vip/draw".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/vip/draw";  vip提款页
                    startActivity(new Intent(this, CashWithdrawalActivity.class));

                } else if ("page/member".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/member";  我的
                    Intent intent = getIntent();
                    intent.putExtra("type", "page/member");
                    setResult(RESULT_OK, intent);
                    finish();
                } else if ("page/member/order".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    //"page/member/order";  我的订单

                    Intent intent = new Intent(this, MyOrderDetailActivity.class);
                    intent.putExtra("orderNo", memberMessagEntity.getBody().getList().get(position).getExtras().getParams().getId());
                    startActivity(intent);
                } else if ("page/material".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    // 一键发圈素材页
                    LoginEntity userInfo =
                            SharedPreferencesUtil.getUserInfo(this);
                    if (!"0".equals(userInfo.getBody().getMember().getType())) {
                        startActivity(new Intent(this, DynamicActivity.class));

                    }

                } else if ("page/vip/fans".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    // （3）会员通知中的新增粉丝：粉丝列表没有跳转到粉丝列表中去
                    LoginEntity userInfo =
                            SharedPreferencesUtil.getUserInfo(this);
                    if (!"0".equals(userInfo.getBody().getMember().getType())) {
                        startActivity(new Intent(this, CustomerListActivity.class).putExtra("memberType", "1"));
                    }


                } else if ("page/vip/subordinate".equals(memberMessagEntity.getBody().getList().get(position).getExtras().getIdfAppPage())) {
                    // （4）会员通知中的新增下级中的下级列表没有跳到下级列表中去
                    LoginEntity userInfo =
                            SharedPreferencesUtil.getUserInfo(this);
                    if (!"0".equals(userInfo.getBody().getMember().getType()) && !"1".equals(userInfo.getBody().getMember().getType())) {
                        startActivity(new Intent(this, CustomerListActivity.class).putExtra("memberType", "2"));
                    }


                }


            } else if (memberMessagEntity.getBody().getList().get(position).getExtras().getType() == 2) {
                //链接跳转内嵌webView

                Intent intent = new Intent(this, H5Activity.class);
                intent.putExtra("title", memberMessagEntity.getBody().getList().get(position).getTitle());
                intent.putExtra("url", memberMessagEntity.getBody().getList().get(position).getExtras().getLink());

                startActivity(intent);

            } else if (memberMessagEntity.getBody().getList().get(position).getExtras().getType() == 3) {
                //版本更新
                loadingDialog = LoadingDialog.newInstance("检查更新中...");
                loadingDialog.show(getFragmentManager());
                upgrade();
            }

        }


    }

    //版本更新
    private void upgrade() {
        Map<String, String> map = new HashMap<>();
        map.put("force", "true");

        OkHttpUtil.getJSON(this, Constant.URL.upgrade, map, this);

    }

    @Override
    public void onCallback() {

    }

    @Override
    public void onClick(View v) {

    }

    private void dismissLoading() {


        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void onProgress(final int rate) {
        ProgressBar pb = downloadDialog.getProgressBar();
        final TextView btnInstall = downloadDialog.getBtnInstall();
        if (pb != null) {
            pb.setProgress(rate);
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (btnInstall != null) {
                    btnInstall.setText("下载中(" + rate + "%)");
                    if (rate == 100) {
                        TextView btnInstall = downloadDialog.getBtnInstall();
                        btnInstall.setSelected(true);
                        btnInstall.setText("安装");
                        btnInstall.setClickable(true);
                        btnInstall.setOnClickListener(MessageListType0Activity.this);
                        jumpInstall();
                    }
                }
            }
        });
    }

    @Override
    public void onBackPressed() {

        if (isNeedLoad) {
            Intent intent = getIntent();
            intent.putExtra("type", "default");
            setResult(RESULT_OK, intent);
        }

        super.onBackPressed();
    }
}
